# -*- coding: utf-8 -*-
"""
日志管理模块

提供统一的日志记录功能，支持文件和控制台输出
"""

import logging
import os
import sys
from logging.handlers import RotatingFileHandler
from typing import Optional

# 添加父目录到路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from core.config import Config


def get_logger(name: str, config: Optional[Config] = None) -> logging.Logger:
    """获取配置好的日志记录器
    
    Args:
        name: 日志记录器名称
        config: 配置对象，如果为None则使用默认配置
        
    Returns:
        配置好的日志记录器
    """
    if config is None:
        config = Config()
    
    logger = logging.getLogger(name)
    
    # 避免重复添加处理器
    if logger.handlers:
        return logger
    
    # 设置日志级别
    log_level = getattr(logging, config.get('logging.level', 'INFO').upper())
    logger.setLevel(log_level)
    
    # 创建格式器
    formatter = logging.Formatter(
        config.get('logging.format', '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    )
    
    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(log_level)
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    
    # 文件处理器
    log_file = config.get('logging.file', 'survey_analyzer.log')
    if not os.path.isabs(log_file):
        log_file = os.path.join(config.get('output.base_dir', 'output'), log_file)
    
    os.makedirs(os.path.dirname(log_file), exist_ok=True)
    
    file_handler = RotatingFileHandler(
        log_file,
        maxBytes=config.get('logging.max_bytes', 10485760),  # 10MB
        backupCount=config.get('logging.backup_count', 5),
        encoding='utf-8'
    )
    file_handler.setLevel(log_level)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    
    return logger


class LoggerMixin:
    """日志记录器混入类"""
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._logger = None
    
    @property
    def logger(self) -> logging.Logger:
        """获取日志记录器"""
        if self._logger is None:
            self._logger = get_logger(self.__class__.__name__)
        return self._logger
    
    def log_info(self, message: str, *args, **kwargs) -> None:
        """记录信息日志"""
        self.logger.info(message, *args, **kwargs)
    
    def log_warning(self, message: str, *args, **kwargs) -> None:
        """记录警告日志"""
        self.logger.warning(message, *args, **kwargs)
    
    def log_error(self, message: str, *args, **kwargs) -> None:
        """记录错误日志"""
        self.logger.error(message, *args, **kwargs)
    
    def log_debug(self, message: str, *args, **kwargs) -> None:
        """记录调试日志"""
        self.logger.debug(message, *args, **kwargs)